import 'package:flutter/material.dart';
import 'package:fluttertest/models/route_model.dart';
import 'package:fluttertest/models/task_model.dart';
import 'package:fluttertest/navigation_result.dart';
import '../../models/type_map.dart';
import '../../utils/event_bus.dart';
import '../../utils/http_client.dart';
import '../../models/delivery_item.dart';
import '../home_screen.dart';

class SummaryScreen extends StatefulWidget {
  final String waybillNumber;

  const SummaryScreen({
    super.key,
    required this.waybillNumber,
  });

  @override
  State<SummaryScreen> createState() => _SummaryScreenState();
}

class _SummaryScreenState extends State<SummaryScreen> {
  bool _isLoading = true;
  TaskModel? taskModel;
  Map<String,Map<String, dynamic>> _totalTypeData = {};
  int _totalDiffCount = 0;
  int _totalOtherCount = 0;
  List<TypeMap>? _allUnit;
  Map<String, bool> _expandedStates = {};


  @override
  void initState() {
    loadAllType().then((_)=>_loadWaybillDetails());
    super.initState();
  }

  Future <void> loadAllType() async {
    try {
      final response = await HttpClient.dio.post('/follower/getAllType');
      if (response.data['code'] == 0) {
        List.of(response.data['data']);
        List<dynamic> l = response.data['data'];
        setState(() {
          _allUnit = l.map((e) => TypeMap.fromJson(e)).toList();
        });
      }
    } catch (e) {
      print(e);
      // loadAllType();
      return;
    }
  }

  String _getTypeText(int type) {
    // 类型转换逻辑
    for (TypeMap e in _allUnit!) {
      if (e.typeId == type) {
        return e.typeName;
      }
    }
    return "未知";
  }

  Future<void> _loadWaybillDetails() async {
    try {
      // 获取运单详情
      final response = await HttpClient.dio.post(
        '/follower/getWaybillInfoDetails',
        data: {
          'waybillNumber': widget.waybillNumber,
        },
      );
      if (response.data['code'] == 0) {
        setState(() {
          _isLoading = false;
          taskModel = TaskModel.fromJson(response.data['data']);
        });

        // 创建类型映射
        final Map<String, Map<String, dynamic>> typeMap = {};
        for (TypeMap type in _allUnit!) {
          typeMap[type.typeId.toString()] = {
            'name': type.typeName,
            'list': [],
            'gds': 0,
            'storeCount': 0,
            'type': type.scene,
          };
        }

        // 统计差异和其他项目
        int totalOtherCount = 0;
        int totalDiffCount = 0;

        for (Sequence sequence in taskModel!.sequences!) {
          // 处理其他详情
          for (DeliveryItem other in sequence.otherDetails) {
            final typeId = other.itemcode.toString();
            if (typeMap.containsKey(typeId)) {
              typeMap[typeId]!['list'].add(other);
              setState(() {
                typeMap[typeId]!['gds'] = (typeMap[typeId]!['gds'] as int) + 1;
              });
              totalOtherCount++;
            }
          }

          // // 处理差异详情
          // final differenceDetails = List<Map<String, dynamic>>.from(
          //     sequence['differenceDetails'] ?? []);
          // for (var diff in differenceDetails) {
          //   final typeId = diff['differenceType'].toString();
          //   if (typeMap.containsKey(typeId)) {
          //     typeMap[typeId]!['list'].add(diff);
          //     typeMap[typeId]!['gds'] = (typeMap[typeId]!['gds'] as int) + 1;
          //     totalDiffCount++;
          //   }
          // }
        }


        // 计算每个类型涉及的店铺数
        typeMap.forEach((key, value) {
          final storeNumbers = (value['list']??[] as List<DeliveryItem>)
              .map((item) => item.shopCode)
              .toSet();
          value['storeCount'] = storeNumbers.length;
        });

        // 移除空列表
        typeMap.removeWhere((key, value) => (value['list'] as List).isEmpty);


        setState(() {
          _totalTypeData = typeMap;
          _totalDiffCount = totalDiffCount;
          _totalOtherCount = totalOtherCount;
        });
        print('${_totalTypeData}|${_totalDiffCount}|${_totalOtherCount}');
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '加载失败')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
      setState(() {
        _isLoading = false;
      });
    }
  }

  String _getStoreStatus(Sequence store) {
    if (store.unArrival == 1) {
      if (store.status == 2) {
        if (store.fadadaStatus == 0) {
          return '到店后跳过';
        } else if (store.fadadaStatus == 1) {
          return '送达后跳过';
        }
      } else if (store.status == 1) {
        return '司机未到店';
      }
      return '状态异常';
    } else if (store.unArrival == 0 &&
        store.status == 3 &&
        store.fadadaStatus == 2) {
      return '完成签收';
    }
    return '状态异常';
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: Colors.blue,
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Text(
              label,
              style: const TextStyle(color: Colors.grey),
            ),
          ),
          Expanded(
            flex: 3,
            child: Text(
              value,
              style: const TextStyle(fontWeight: FontWeight.w500),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDifferenceItem(Map<String, dynamic> diff) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildInfoRow('商品名称:', diff['goodsName'] ?? ''),
            _buildInfoRow('商品编码:', diff['goodsNumber'] ?? ''),
            _buildInfoRow('差异数量:', '${diff['diffCount'] ?? 0}'),
            _buildInfoRow('差异原因:', _getTypeText(diff['differenceType'] ?? 0)),
            _buildInfoRow('说明:', diff['diffReason'] ?? ''),
          ],
        ),
      ),
    );
  }

  Widget _buildOtherItem(DeliveryItem other) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildInfoRow('项目类型:', _getTypeText(other.itemcode ?? 0)),
            _buildInfoRow('实收数量:', '${other.actualamount ?? 0}'),
            _buildInfoRow('单位:', other.reason ?? ''),
            _buildInfoRow('备注:', other.comment ?? ''),
          ],
        ),
      ),
    );
  }

  Widget _buildTypeRow({
    required String title,
    required int storeCount,
    required dynamic amount,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Expanded(
            flex: 4,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('项目类型'),
                Text(
                  title,
                  style: const TextStyle(color: Colors.grey),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 4,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Text('涉及门店'),
                Text(
                  '$storeCount家',
                  style: const TextStyle(color: Colors.grey),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 4,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                const Text('数量'),
                Text(
                  '$amount',
                  style: const TextStyle(color: Colors.grey),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _showFinishDialog() async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('回车交接提示'),
        content: const Text('确定完成回车交接吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop<NavigationResult>(context, NavigationResult(
              message: "回车交接完成"
            )),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              eventBus.notifyTaskStatusChanged();
              Navigator.pop(context, true);
          } ,
            child: const Text('确认'),
          ),
        ],
      ),
    );

    if (result == true) {
      await _onFinish();
    }
  }

  Future<void> _onFinish() async {
    try {
      final response = await HttpClient.dio.post(
        '/follower/backFinish',
        data: {
          'waybillNumber': widget.waybillNumber,
          'clause':[],
          'totalDiffCount': _totalDiffCount,
          'totalOtherCount':_totalOtherCount,
          'totalTypeDate': _totalTypeData
        },
      );
      print(response.data);
      if (response.data['code'] == 0) {
        if (mounted) {
          Navigator.of(context).popUntil((route) => route.isFirst);
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['message'] ?? '操作失败')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    print(123);
    if (_isLoading) {
      return Container(
        color: Colors.black12,  // 半透明背景
        child: const Center(
          child: Card(
            child: Padding(
              padding: EdgeInsets.all(16),
              child: CircularProgressIndicator(),
            ),
          ),
        ),
      );
    }
    return Scaffold(
      appBar: taskModel!.status==6?AppBar(title: const Text('完成单详情')):AppBar(title: const Text('送货汇总')),
      body:
      WillPopScope( onWillPop: () async {
        Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>const HomeScreen()),(route)=>false);
        return false;
      },child:SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (taskModel?.status ==4||taskModel?.status ==5 ||taskModel?.status ==6) ...[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: taskModel!.sequences!.length,
                      itemBuilder: (context, index) {
                        final store = taskModel!.sequences![index];
                        final hasOther = store.otherDetails?.isNotEmpty == true;
                        return Card(
                          child: ExpansionTile(
                            initiallyExpanded: hasOther,
                            leading: const Icon(Icons.store),
                            title: Text('${store.storeNumber}.${store.storeName}'),
                            subtitle: Text('${_getStoreStatus(store)}\n周转箱数:${store.realTrunBox}'),
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(16),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    if (store.otherDetails!.isEmpty)
                                      Text("签收项为空"),
                                    // if (store['differenceDetails']?.isNotEmpty) ...[
                                    //   _buildSectionTitle('差异物品'),
                                    //   ...store['differenceDetails'].map((diff) =>
                                    //       _buildDifferenceItem(diff)),
                                    // ],
                                    if (hasOther) ...[
                                      _buildSectionTitle('其他签收项'),
                                      ...store.otherDetails.map((other) =>
                                          _buildOtherItem(other)),
                                    ],
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                    // ExpansionPanelList(
                    //   elevation: 1,
                    //   expansionCallback: (index,value){
                    //     setState(() {
                    //       taskModel?.sequences?[index].isExpanded = taskModel?.sequences![index].isExpanded??true;
                    //     });
                    //   },
                    //   expandedHeaderPadding: EdgeInsets.zero,
                    //   children:taskModel?.sequences?.map<ExpansionPanel>((Sequence store) {
                    //     setState(() {
                    //       store.isExpanded = store.otherDetails.isNotEmpty?true:false;
                    //     });
                    //     return ExpansionPanel(
                    //       headerBuilder: (context, isExpanded) {
                    //         return ListTile(
                    //           leading: const Icon(Icons.store),
                    //           title: Text(
                    //               '${store.storeNumber}.${store.storeName}'),
                    //           subtitle: Text(_getStoreStatus(store)),
                    //         );
                    //       },
                    //       body: Padding(
                    //         padding: const EdgeInsets.all(16),
                    //         child: Column(
                    //           crossAxisAlignment: CrossAxisAlignment.start,
                    //           children: [
                    //             // if (store['differenceDetails']
                    //             //     ?.isNotEmpty) ...[
                    //             //   _buildSectionTitle('差异物品'),
                    //             //   ...store['differenceDetails'].map(
                    //             //       (diff) => _buildDifferenceItem(diff)),
                    //             // ],
                    //             if (store.otherDetails!.isNotEmpty) ...[
                    //               _buildSectionTitle('其他签收项'),
                    //               ...store.otherDetails.map(
                    //                       (DeliveryItem other) => _buildOtherItem(other)),
                    //             ],
                    //           ],
                    //         ),
                    //       ),
                    //       isExpanded:store.isExpanded
                    //     );
                    //   }).toList()??[]
                    // ),

                    const SizedBox(height: 20),
                    _buildSectionTitle('汇总'),
                    _buildInfoRow('空周转箱数:', '${taskModel?.emptyTrunBox}'),
                      _buildInfoRow(
                          '真实空周转箱数:', '${taskModel?.realEmptyTrunBox}'),
                    ..._totalTypeData.values // 获取所有的 Map<String, dynamic>
                        .where((item) => item['type'] == 2) // 过滤出 type 为 3 的项
                        .map(
                          (other) => _buildTypeRow(
                        title: other['name'], // 使用过滤后的项来获取 name
                        storeCount: other['storeCount'],
                        amount: other['gds'],
                      ),
                    ),
                    if (_totalOtherCount > 0) ...[
                      _buildSectionTitle('回收汇总'),
                      _buildInfoRow('回收项目数:', '$_totalOtherCount'),
                      ..._totalTypeData.values // 获取所有的 Map<String, dynamic>
                          .where((item) => item['type'] == 3) // 过滤出 type 为 3 的项
                          .map(
                            (other) => _buildTypeRow(
                          title: other['name'], // 使用过滤后的项来获取 name
                          storeCount: other['storeCount'],
                          amount: other['gds'],
                        ),
                      ),
                    ],
                  ],
                ),
                const SizedBox(height: 20),
                if(taskModel?.status!=6)
                  ElevatedButton(
                    onPressed:_isLoading?null: _showFinishDialog,
                    style: ElevatedButton.styleFrom(
                        minimumSize: const Size.fromHeight(48),
                        backgroundColor: Colors.green
                    ),
                    child: const Text('回车交接完成',style: TextStyle(color: Colors.white)),
                  ),
              ],
            ],
          ),
        ),
      )
    );
  }

// ... 其他辅助方法
}
